package is.model.dao.search;

import is.NullUtil;
import is.model.bean.Department;
import java.sql.*;
import java.util.LinkedList;
import java.util.List;

/**
 *
 * @author aspr0
 */
public class DepartmentSearch extends AbstractSearch
{
    /**
     *
     * @param strict not used
     * @param initialBean
     * @param connection
     * @return
     * @throws SQLException
     */
    public static List<Department> search(Boolean strict, Department initialBean, Connection connection) throws
            SQLException
    {
        String where = organizeRegex(NullUtil.toString(initialBean.getId()), initialBean.getFields(), initialBean.getValues());

        String query = String.format(QUERY_CANVAS, initialBean.getTableName(), where);

        PreparedStatement statement = connection.prepareStatement(query);
        Integer parameterN = 0;

        Integer id = initialBean.getId();
        /* If value isnt empty, it should be placed in query within regex mask */
        if (id != null)
        {
            parameterN++;
            statement.setString(parameterN, String.format(REGEX_CANVAS, id));
        }

        String name = initialBean.getName();
        if (name != null)
        {
            parameterN++;
            statement.setString(parameterN, String.format(REGEX_CANVAS, prepareMask(name)));
        }

        Integer parentId = initialBean.getParentId();
        if (parentId != null)
        {
            parameterN++;
            statement.setString(parameterN, String.format(REGEX_CANVAS, parentId));
        }

        Integer bossId = initialBean.getBossId();
        if (bossId != null)
        {
            parameterN++;
            statement.setString(parameterN, String.format(REGEX_CANVAS, bossId));
        }

        Integer regionId = initialBean.getRegionId();
        if (regionId != null)
        {
            parameterN++;
            statement.setString(parameterN, String.format(REGEX_CANVAS, regionId));
        }

        statement.execute();

        ResultSet resultSet = statement.getResultSet();

        List<Department> beans = new LinkedList<Department>();

        while (resultSet.next())
        {
            Department listBean = (Department) initialBean.clone();
            listBean.processResultSet(resultSet);
            beans.add(listBean);
        }
        resultSet.close();

        return beans;
    }
}
